import React, { useState, useContext } from "react";
import {
  StyleSheet,
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StatusBar,
  Platform,
  Alert,
  Keyboard,
} from "react-native";
import { AntDesign } from "@expo/vector-icons";
import queryApi from "../../api/query";
import AsyncStorage from "@react-native-async-storage/async-storage";

const UpdatePassword = ({ navigation }) => {
  const [oldPassword, setOldPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const editPassword = async (updateData) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      const result = await queryApi.patch("/user/password", updateData, {
        headers: { Authorization: token },
      });
      if (result.data.message == "success") {
        setOldPassword("");
        setNewPassword("");
        setConfirmPassword("");
        Keyboard.dismiss();
        Alert.alert("成功", "修改密码成功", [{ text: "确定" }]);
      } else {
        Alert.alert("失败", "修改密码出错", [{ text: "确定" }]);
      }
    } catch (err) {
      Alert.alert("失败", "修改密码出错", [{ text: "确定" }]);
      console.log("修改密码出错", err);
    }
  };
  const updatePasswordHandler = (oldPassword, newPassword, confirmPassword) => {
    if (
      oldPassword.length == 0 ||
      newPassword.length == 0 ||
      confirmPassword.length == 0
    ) {
      Alert.alert("输 入 错 误 ", "输 入 不 能 为 空", [{ text: "确定" }]);
      return;
    }
    if (newPassword != confirmPassword) {
      Alert.alert("输 入 错 误 ", "新 密 码 和 确 认 密 码 不 一 致", [
        { text: "确定" },
      ]);
      return;
    }
    if (
      oldPassword.length < 8 ||
      newPassword.length < 8 ||
      confirmPassword.length < 8
    ) {
      Alert.alert("输 入 错 误 ", "密 码 长 度 小 于 8 位", [{ text: "确定" }]);
      return;
    }
    editPassword({
      oldPassword: oldPassword,
      newPassword: newPassword,
    });
  };

  return (
    <View style={styles.container}>
      <View style={styles.backgroundTop}></View>

      <View style={styles.editModal}>
        <TouchableOpacity
          onPress={() => navigation.goBack()}
          style={styles.closeStyle}
        >
          <AntDesign name="close" size={20} color="black" />
        </TouchableOpacity>
        <View style={styles.headerView}>
          <Text style={styles.headerText}>修改密码</Text>
        </View>

        <View style={[styles.addItem]}>
          <Text style={styles.title}>旧密码:</Text>
          <TextInput
            style={{ fontSize: 16, marginRight: 5 }}
            maxLength={20}
            value={oldPassword}
            secureTextEntry={true}
            textAlign="right"
            placeholder="请输入旧密码"
            onChangeText={(text) => {
              setOldPassword(text);
            }}
          />
        </View>

        <View style={[styles.addItem]}>
          <Text style={styles.title}>新密码:</Text>
          <TextInput
            style={{ fontSize: 16, marginRight: 5 }}
            placeholder="请输入新密码"
            maxLength={20}
            value={newPassword}
            secureTextEntry={true}
            textAlign="right"
            onChangeText={(text) => {
              setNewPassword(text);
            }}
          />
        </View>

        <View style={styles.addItem}>
          <Text style={styles.title}>确认密码:</Text>
          <TextInput
            style={{ fontSize: 16, marginRight: 5 }}
            placeholder="请输入确认密码"
            maxLength={20}
            secureTextEntry={true}
            value={confirmPassword}
            textAlign="right"
            onChangeText={(text) => {
              setConfirmPassword(text);
            }}
          />
        </View>

        <View style={styles.buttonOptions}>
          <TouchableOpacity
            style={styles.cancel}
            onPress={() => navigation.goBack()}
          >
            <Text style={styles.cancelText}>取消</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.confirm}
            onPress={() => {
              updatePasswordHandler(oldPassword, newPassword, confirmPassword);
            }}
          >
            <Text style={styles.confirmText}>确定</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff9ed",
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
  },
  backgroundTop: {
    width: "100%",
    height: "35%",
    // backgroundColor: "#6488e5",
    backgroundColor: "#b7e5e3",
    borderBottomLeftRadius: 30,
    borderBottomRightRadius: 30,
    position: "absolute",
    top: 0,
  },
  closeStyle: {
    position: "absolute",
    left: 25,
    top: 25,
  },
  headerView: {
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 15,
  },
  headerText: {
    fontSize: 20,
    fontWeight: "bold",
  },
  editModal: {
    backgroundColor: "#fff",
    padding: 20,
    width: "90%",
    borderRadius: 20,
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.1, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
  },
  addItem: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
    height: 50,
  },
  title: {
    fontSize: 16,
    color: "#22254c",
    width: 90,
  },
  buttonOptions: {
    flexDirection: "row",
    justifyContent: "center",
    alignContent: "center",
    padding: 15,
    marginBottom: 5,
  },
  cancel: {
    flex: 3,
    padding: 10,
    marginRight: 20,
    borderWidth: 1.5,
    borderColor: "#F9be7d",

    alignItems: "center",
    justifyContent: "center",
    borderRadius: 5,
  },
  confirm: {
    borderRadius: 5,
    flex: 7,
    padding: 10,
    backgroundColor: "#F9be7d",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  cancelText: {
    fontSize: 16,
    color: "#22254c",
  },
  confirmText: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
});

export default UpdatePassword;
